import datetime
import os
import json
import urllib.request
import rospy
import actionlib


from chatgpt_ros_msg.srv import chat, chatRequest, chatResponse
from zhipuai import ZhipuAI

class ChatServer:
    """
    Chatbot class for conversation.
    """
    def __init__(self,api_key):
        self.glm_client = ZhipuAI(api_key=api_key)
        server = rospy.Service("chat", chat, self.chat)
        
    def chat(self, req):
        """
        Chat with chatgpt model.
        :param content: User input
        :return: result
        """
        output = self.glm_client.chat.completions.create(
            model="glm-4",  # 填写需要调用的模型名称
            messages=[
                {"role": "user","content": req.prompt},
            ],
        )
        response = chatResponse()
        rospy.loginfo("chat服务器数据为%s,响应结果为：%s", req, output.choices[0].message.content)
        response.result = output.choices[0].message.content
        return response
    


def main():
    rospy.init_node("chat_action_server")

    chat_action_server = ChatServer("a0cf45792327b905a6d95bcdccc9d4ac.WDXkhvuddSg7KAQk")

    rospy.spin()


if __name__ == '__main__':
    main()
